<?php declare(strict_types=1);

// 立即加载.env文件的配置
(function () {
    if (file_exists(__DIR__ . '/../.env')) {
        $envLines = file_get_contents(__DIR__ . '/../.env');
        foreach (explode("\n", $envLines) as $key => $assignment) {
            $assignment = trim($assignment);
            if ($assignment === '') {
                continue;
            }
            
            if (strpbrk($assignment[0], '#') !== false) {
                continue;
            }
            
            [$name, $value] = explode('=', $assignment);
            if ($value === '') {
                $value = '';
            } elseif (strpbrk($value[0], '"\'') !== false) {
                if (strripos($value, $value[0]) === 0) {
                    throw new Exception(sprintf('env config error, assignment %s in .evn:%d', $assignment, $key + 1));
                }
                $value = mb_substr($value, 1, strripos($value, $value[0]) - 1);
            } else {
                [$value] = explode(' #', $value, 2);
            }
            
            $name  = trim($name);
            $value = trim($value);
            
            if ($value === 'true') {
                $value = true;
            } elseif ($value === 'false') {
                $value = false;
            }
            
            if (function_exists('apache_setenv')) {
                if (apache_setenv($name, $value) === false) {
                    throw new Exception(sprintf('env config error, assignment %s in .evn:%d', $assignment, $key + 1));
                }
            }
            
            if (function_exists('putenv')) {
                if (putenv($name . '=' . $value) === false) {
                    throw new Exception(sprintf('env config error, assignment %s in .evn:%d', $assignment, $key + 1));
                }
            }
            
            $_ENV[$name]    = $value;
            $_SERVER[$name] = $value;
        }
    }
})();

function env(string $name = null, $default = null)
{
    if ($name) {
        return isset($_ENV[$name]) ? $_ENV[$name] : $default;
    } else {
        return $_ENV;
    }
}